<template>
  <el-form :model="temp" :rules="rules" ref="ruleForm" label-position="left">
    <el-form-item label="旧密码" prop="usedPassword">
      <el-input type="password" v-model="temp.usedPassword" size="mini" autocomplete="on"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="password">
      <el-input type="password" v-model="temp.password" size="mini" autocomplete="on"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input type="password" v-model="temp.confirmPassword" size="mini" autocomplete="on"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSave" size="mini">修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { validPassword } from "@/utils/validate";
import { resetPwd } from "@/api/account";

export default {
  name: "ResetPassword",
  data() {
    var checkPassword = (rule, value, callback) => {
      if (value === undefined) {
        return callback(new Error("请输新入密码"));
      } else if (!validPassword(value)) {
        return callback(new Error("请输入正确的密码，长度为6~32位字符"));
      } else if (value === this.temp.usedPassword) {
        return callback(new Error("新密码与旧密码一致"));
      } else {
        return callback();
      }
    };
    var checkUsedPassword = (rule, value, callback) => {
      if (value === undefined) {
        return callback(new Error("请输入旧密码"));
      } else if (!validPassword(value)) {
        return callback(new Error("请输入正确的密码，长度为6~32位字符"));
      } else {
        return callback();
      }
    };
    var checkConfirmPassword = (rule, value, callback) => {
      if (value === undefined) {
        return callback(new Error("确认密码不能为空"));
      } else if (value === this.temp.password) {
        return callback();
      } else {
        return callback(new Error("确认密码与新密码不一致"));
      }
    };
    return {
      temp: {
        password: undefined, //新密码
        usedPassword: undefined, //旧密码
        confirmPassword: undefined //确认密码
      },
      rules: {
        usedPassword: [
          { validator: checkUsedPassword, required: true, trigger: "blur" }
        ],
        password: [
          { validator: checkPassword, required: true, trigger: "blur" }
        ],
        confirmPassword: [
          { validator: checkConfirmPassword, required: true, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    handleSave() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          const loading = this.$loading({ text: "正在重置密码..." });
          resetPwd(this.temp)
            .then(response => {
              loading.close();
              if (response.success) {
                location.reload();
              }
            })
            .catch(err => {
              loading.close();
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>